package com.angel.web.health;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.angel.core.Constants;
import com.angel.core.base.JsonEntity;
import com.angel.core.util.CodeUtil;
import com.angel.core.util.JsonResult;
import com.angel.core.util.JsonUtil;
import com.angel.core.util.JsonUtils;
import com.angel.core.util.Pager;
import com.angel.core.util.TreeNodes;
import com.angel.health.BuzAssessment;
import com.angel.health.BuzCustomer;
import com.angel.health.BuzCustomerLog;
import com.angel.health.BuzLabel;
import com.angel.health.BuzSurvey;
import com.angel.health.SysArea;
import com.angel.health.ln.WangYi;
import com.angel.provider.app.WangYiProvider;
import com.angel.provider.health.BuzAssessmentProvider;
import com.angel.provider.health.BuzCustomerLogProvider;
import com.angel.provider.health.BuzCustomerProvider;
import com.angel.provider.health.BuzLabelProvider;
import com.angel.provider.health.BuzSurveyProvider;
import com.angel.provider.sys.SysManagerAreaProvider;
import com.github.pagehelper.StringUtil;

import net.sf.json.JSONArray;

/**
 * 客户信息管理
 * 
 * @author cheng sir
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/customer")
public class BuzCustomerController {

	@Autowired
	private BuzCustomerProvider customerService;
	@Autowired
	private SysManagerAreaProvider sysManagerAreaProvider;
	@Autowired
	private BuzSurveyProvider buzSurveyProvider;
	@Autowired
	private BuzLabelProvider labelProvider;
	@Autowired
	private BuzAssessmentProvider buzAssessmentProvider;
	@Autowired
	private WangYiProvider wyService;
	@Autowired
	private BuzCustomerLogProvider bclProvider;

	/**
	 * 用户登录
	 */
	@ResponseBody
	@RequestMapping(value = "login", produces = "application/json; charset=utf-8")
	public String login(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		List<Map<String, Object>> list = customerService.findAll(buzCustomer);
		if (list != null && list.size() > 0) {
			return JsonUtil.toJson(new JsonEntity("200", JsonUtil.toJson(list.get(0))));
		}
		return JsonUtil.toJson(new JsonEntity("-1", "帐号密码不正确！"));
	}

	/**
	 * 查询用户
	 * 
	 * @param request
	 * @param buzCustomer
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request, @ModelAttribute("buzCustomer") BuzCustomer buzCustomer,
			Pager pager) {
		buzCustomer.setEnable(1);
		pager = customerService.findAll(buzCustomer, pager);
		request.setAttribute("data", pager);
		request.setAttribute("re", buzCustomer.getSearchVal());
		return "member/memberinformation";
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param buzCustomer
	 * @return
	 */
	@RequestMapping(value = "addCustomer")
	public String addCustomer(HttpServletRequest request, @ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		List<Map<String, Object>> customerCount = customerService.findCustomerByPhone(buzCustomer);
		if (customerCount.size() > 0) {
			request.setAttribute("isHave", "用户已存在!");
			return "member/memberinformation_add";
		}
		String createUser;
		try {
			createUser = wyService
					.createUser(JsonUtil.toJson(new WangYi(buzCustomer.getMemPhone(), buzCustomer.getName())));
			if (!StringUtils.isEmpty(createUser)) {
				Map<String, String> map = JsonUtil.jsonStringToMap(createUser);
				if ("200".equals(map.get("code"))) {
					buzCustomer.setToken(map.get("token"));
				}
			}
		} catch (Exception e) {
		}
		String username = (String) request.getSession().getAttribute("user");
		buzCustomer.setEnable(1);
		buzCustomer.setLabelId(1);
		buzCustomer.setCreateBy(username);
		buzCustomer.setUpdateBy(username);
		int i = customerService.insert(buzCustomer);
		
		//增加客户日志
		BuzCustomerLog bcl = new BuzCustomerLog();
		bcl.setContent("您注册成功！");
		bcl.setCustomerId(buzCustomer.getId());
		bcl.setType(1);
		bclProvider.insert(bcl);

		buzCustomer.setCode(CodeUtil.createCode(null, Constants.CUSTOMERNUM, buzCustomer.getId()));
		customerService.updateById(buzCustomer);

		return "redirect:/customer/index";
	}

	/**
	 * 删除用户
	 */
	@ResponseBody
	@RequestMapping(value = "/del")
	public String del(String ids) {
		try {
			String[] idlist = ids.split(",");
			if (idlist != null) {
				BuzCustomer b = null;
				for (int i = 0; i < idlist.length; i++) {
					b = new BuzCustomer();
					b.setId(Integer.parseInt(idlist[i]));
					customerService.delById(b);
				}
			}
			return JsonUtil.toJson(new JsonEntity("200", JsonUtil.toJson(0)));
		} catch (Exception e) {
			return JsonUtil.toJson(new JsonEntity("-1", "修改失败"));
		}
	}

	/**
	 * 完善信息
	 */
	@ResponseBody
	@RequestMapping(value = "/edit", produces = "application/json; charset=utf-8")
	public String editCustomer(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		int updateById = customerService.updateById(buzCustomer);
		if (updateById > 0) {
			BuzCustomer bc = new BuzCustomer();
			bc.setId(buzCustomer.getId());
			List<Map<String, Object>> list = customerService.findAll(bc);
			return JsonUtil.toJson(new JsonEntity("200", JsonUtil.toJson(list.get(0))));
		}
		return JsonUtil.toJson(new JsonEntity("-1", "修改失败"));
	}

	/**
	 * 根据旧密码修改密码
	 */
	@ResponseBody
	@RequestMapping(value = "upfop", produces = "application/json; charset=utf-8")
	public String updatePwordForOldPword(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		if (StringUtils.isEmpty(buzCustomer.getOldPassword())) {
			return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
		}
		BuzCustomer bc = new BuzCustomer();
		bc.setMemPhone(buzCustomer.getMemPhone());
		bc.setPassword(buzCustomer.getOldPassword());
		List<Map<String, Object>> list = customerService.findAll(bc);
		if (list.size() > 0) {
			buzCustomer.setId(Integer.parseInt(list.get(0).get("id").toString()));
			int updateById = customerService.updateById(buzCustomer);
			if (updateById > 0) {
				return JsonUtil.toJson(new JsonEntity("200", "修改成功"));
			}
		}
		return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
	}

	/**
	 * 模糊查询用户信息 用户名称 || 手机号||email
	 * 
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "findCustomerByUser", produces = "application/json; charset=utf-8")
	public String findCustomerByUser(String user) {
		List<Map<String, Object>> list = customerService.findCustomerByUser(user);
		return JsonUtil.toJson(list);
	}

	/**
	 * 跳转添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/toAdd")
	public String toAdd() {
		return "member/memberinformation_add";
	}

	/**
	 * 跳转修改/查看页面
	 * 
	 * @return
	 */
	@RequestMapping("/toLook/{id}/{k}/{m}")
	public String toLook(HttpServletRequest request, @PathVariable("id") Integer id, @PathVariable("k") String k,
			@PathVariable("m") String m) {
		BuzCustomer f = customerService.getById(id);
		JSONArray ar = JSONArray.fromObject(f.getAppendAddress());
		request.setAttribute("appendAddress", ar);
		request.setAttribute("re", f);
		request.setAttribute("k", k);
		request.setAttribute("m", m);
		return "member/memberinformation_look";
	}

	/**
	 * 查看修改
	 * 
	 * @param buzCustomer
	 * @param request
	 * @return
	 */
	@RequestMapping("/update")
	public String update(BuzCustomer buzCustomer, HttpServletRequest request) {
		int i = customerService.updateById(buzCustomer);
		try {
			String updateUinfo = wyService.updateUinfo(JsonUtil.toJson(buzCustomer));
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		if (i == 1) {
			return "redirect:/customer/toLook/" + buzCustomer.getId() + "/2/success";
		}
		return "redirect:/customer/toLook/" + buzCustomer.getId() + "/2/error";
	}

	/**
	 * ajaxLoad区域
	 * 
	 * @param buzCustomer
	 * @param request
	 * @return
	 */
	@RequestMapping("/ajaxLoadAddress")
	public void ajaxLoadAddress(HttpServletResponse response, SysArea area) {
		JsonResult.sendResult(response, JsonUtils.toJson(sysManagerAreaProvider.findByPid(area)));
	}

	/**
	 * 问卷调查跳转
	 * 
	 * @return
	 */
	@RequestMapping("/toSurveyRepor/{id}")
	public String toSurveyRepor(@PathVariable("id") String id, HttpServletRequest request) {
		BuzSurvey buzSurvey = buzSurveyProvider.findByCustomerId(id);
		BuzCustomer buzCustomer = customerService.getById(Integer.parseInt(id));
		request.setAttribute("id", id);
		request.setAttribute("r", buzCustomer);
		if (buzSurvey != null) {
			request.setAttribute("re", buzSurvey);
			request.setAttribute("result", buzSurvey.getContent());
		}
		return "member/surveyRepor";
	}
	
	/**
	 * 问卷调查
	 * @param type 问卷类型 1.常规问卷2生化问卷3心理问卷4女性问卷5中医问卷
	 * @return
	 */
	@RequestMapping("/saveSurveyRepor")
	public String saveSurveyRepor(String contentType,HttpServletRequest request, BuzSurvey buzSurvey) {
		BuzSurvey b = buzSurveyProvider.findByCustomerId((buzSurvey.getCustomerId()).toString());
		if (b != null) {
			buzSurveyProvider.updateSurvey(buzSurvey);
//			if(!StringUtil.isEmpty(buzSurvey.getContentTional())){
//				BuzAssessment search = new BuzAssessment();
//				search.setCustomerId(buzSurvey.getCustomerId());
//				List<Map<String, Object>> list = buzAssessmentProvider.findAssessmentAll(search);
//				BuzAssessment ba = new BuzAssessment();
//				ba.setCustomerId(buzSurvey.getCustomerId());
//				ba.setSurveyId(buzSurvey.getId());
//				if (list.size() == 0) {
//					ba.setEnable(1);
//					buzAssessmentProvider.insert(ba);
//					ba.setCode(CodeUtil.createCode(null, Constants.ASSESSMENT, ba.getId()));
//					buzAssessmentProvider.updateById(ba);
//				} else {
//					String id = list.get(0).get("id").toString();
//					ba.setId(Integer.parseInt(id));
//					buzAssessmentProvider.updateById(ba);
//				}
//			}
			request.setAttribute("id", b.getCustomerId());
			request.setAttribute("re", b);
		} else {
			buzSurvey.setSurveyTime(new Date());
			buzSurveyProvider.save(buzSurvey);
			/**
			 * 添加慢性评估》问卷调查
			 */
//			BuzAssessment search = new BuzAssessment();
//			search.setCustomerId(buzSurvey.getCustomerId());
//			List<Map<String, Object>> list = buzAssessmentProvider.findAssessmentAll(search);
//			BuzAssessment ba = new BuzAssessment();
//			ba.setCustomerId(buzSurvey.getCustomerId());
//			ba.setSurveyId(buzSurvey.getId());
//			if (list.size() == 0) {
//				ba.setEnable(1);
//				buzAssessmentProvider.insert(ba);
//				ba.setCode(CodeUtil.createCode(null, Constants.ASSESSMENT, ba.getId()));
//				buzAssessmentProvider.updateById(ba);
//			}else {
//				String id = list.get(0).get("id").toString();
//				ba.setId(Integer.parseInt(id));
//				buzAssessmentProvider.updateById(ba);
//			}
			request.setAttribute("id", buzSurvey.getCustomerId());
			request.setAttribute("re", buzSurvey);
		}
		
		
		if("1".equals(contentType)){
			request.setAttribute("result", b==null?"":b.getContentTional());
			return "member/surveyTional";
		}else if("2".equals(contentType)){
			request.setAttribute("result", b==null?"":b.getContentChemical());
			return "member/surveyChemical";
		}else if("3".equals(contentType)){
			request.setAttribute("result", b==null?"":b.getContentPsy());
			return "member/surveyPsy";
		}else if("4".equals(contentType)){
			request.setAttribute("result", b==null?"":b.getContentWomen());
			return "member/surveyWomen";
		}else if("5".equals(contentType)){
			return "";
		}else{
			return "redirect:/customer/toSurveyRepor/" + buzSurvey.getCustomerId();
		}
	}

	/**
	 * 问卷调查输出pdf数据
	 * 
	 * @return
	 */
	@RequestMapping("/pDFByCustomerId/{id}")
	public void pDFByCustomerId(HttpServletRequest request, @PathVariable("id") String id) {
		Map b = buzSurveyProvider.PDFByCustomerId(id);
		System.out.println(JsonUtils.toJson(b));
	}

	// 查询所有会员
	@RequestMapping(value = "findAllCustomer", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String findAllCustomer(BuzCustomer customer, String method) {
		List<BuzCustomer> list = customerService.findAllCustomer(customer);
		List<TreeNodes> treeList = new ArrayList<TreeNodes>();
		for (BuzCustomer cust : list) {
			TreeNodes node = new TreeNodes();
			node.setId(cust.getId());
			node.setpId(cust.getLabelId());
			String fullName = "";
			if ("1".equals(method)) {
				if (!StringUtils.isEmpty(cust.getName())) {
					fullName += cust.getName() + ",";
				}
				if (!StringUtils.isEmpty(cust.getMemPhone())) {
					fullName += cust.getMemPhone() + ",";
				}
			} else {
				if (!StringUtils.isEmpty(cust.getName())) {
					fullName += cust.getName() + ",";
				}
				if (!StringUtils.isEmpty(cust.getEmail())) {
					fullName += cust.getEmail() + ",";
				}
			}
			if (!StringUtils.isEmpty(fullName)) {
				fullName = fullName.substring(0, fullName.length() - 1);
			}
			node.setName(fullName);
			treeList.add(node);
		}
		List<BuzLabel> labelList = labelProvider.findAllLabel();
		for (BuzLabel buzLabel : labelList) {
			TreeNodes node = new TreeNodes();
			node.setId(buzLabel.getId());
			node.setName(buzLabel.getName());
			treeList.add(node);
		}
		return JsonUtil.toJson(treeList);
	}
}
